import React, {PureComponent, Fragment} from 'react';
import moment from 'moment';
import {connect} from 'dva';
import {
  Badge,
  Button,
  Form,
  Table,
  Tabs,
  DatePicker,Icon,Modal
} from 'antd';
import {ellipsis2,timeStamp,todayLastSecond} from './../../../utils/utils';
import find from 'lodash/find'
import MyPagination from './../../../components/MyPagination/index'
import filter from 'lodash/filter'
import findIndex from 'lodash/findIndex'
import request from './../../../utils/request';
// import ChartData from "./ChartData";
const FormItem = Form.Item;
const { TabPane } = Tabs;

@connect(({ loading}) => ({
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    console.log('this.props',this.props)
    this.id=this.props.id
    this.name=this.props.name
    this.permissions = JSON.parse(localStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, {name: 'location_add_and_edit'}),
      showdelBtn: find(this.permissions, {name: 'location_delete'}),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      name: '',
      number: '',
      status: '',
      editRecord: {},
      started_at: moment().format('YYYY-MM-DD 00:00:00'),
      ended_at: todayLastSecond(),
      chartModal: false,chartData:[],chartKey:'',
      tabPanes:[{
        name:'设备信息',
        key:'device'
      },
        {
        name:'球阀',
        key:'ball_valve'
      }],
      online_logs:{
        meta: {total: 0, per_page: 0,current_page:1},
        data:[],
        loading:false,
      },
      device_0:{
        meta: {total: 0, per_page: 0,current_page:1},
        data:[],
        loading:false,
      },

      ball_valve_0:{
        meta: {total: 0, per_page: 0,current_page:1},
        data:[],loading:false,
      },

    };
  }


  componentDidMount() {
    console.log('config_data',this.props.config_data)
    this.setState({
      tableY: document.querySelector('.table-page').offsetHeight - 195
    })
    const config_data=this.props.config_data;
    let tabPanes=this.state.tabPanes;
    // this.fetchLog({
    //   page:1,
    //   per_page:20,
    // })
    this.fetch({
      type:'device',
      channel:0,
      page:1,
      per_page:30,
    })
    for(let i=0;i<1;i++){
      this.fetch({
        type:'ball_valve',
        channel:i,
        page:1,
        per_page:30,
      })
    }
  }
  fetch=(params)=>{
    const that=this;
    this.setState({
      [`${params.type}_${params.channel}`]:{
        meta:this.state[`${params.type}_${params.channel}`].meta,
        data:this.state[`${params.type}_${params.channel}`].data,
        loading:true
      }
    })
    ///operation_logs
    request(`/workstations/${this.id}/historical_data`, {
    // request(`/operation_logs`, {
      method: 'GET',
      params:{
        ...params,
        started_at:this.state.started_at,
        ended_at:this.state.ended_at,
      }
    }).then(response=>{

      if(response.status===200){
        that.setState({
          [`${params.type}_${params.channel}`]:{
            meta:{total: response.data.total, per_page: response.data.per_page,current_page:response.data.current_page},
            data:response.data.data,
            loading:false
          }
        })
      }
    });
  }
  fetchLog=(params)=>{
    const that=this;
    this.setState({
      online_logs:{
        meta:this.state.online_logs.meta,
        data:this.state.online_logs.data,
        loading:true
      }
    })
    ///operation_logs
    request(`/rtus/${this.id}/online_logs`, {
      // request(`/operation_logs`, {
      method: 'GET',
      params:{
        ...params,
        started_at:this.state.started_at,
        ended_at:this.state.ended_at,
      }
    }).then(response=>{

      if(response.status===200){
        that.setState({
          online_logs:{
            meta:response.data.meta,
            data:response.data.data,
            loading:false
          }
        })
      }
    });
  }
  resize = ()=> {
    this.setState({
      tableY: document.querySelector('.table-page').offsetHeight - 205
    })
  }

  componentWillUnmount() {
    console.log('componentWillUnmount')
    window.removeEventListener('resize', this.resize)
  }



  renderSimpleForm() {

    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label={
          '开始日期'
        }>
          {getFieldDecorator('started_at', {initialValue: moment(moment().format('YYYY-MM-DD 00:00:00'))})(<DatePicker allowClear={false}
                                                                                 showTime={{ format: 'HH:mm:ss' }}
                                                                                 format="YYYY-MM-DD"/>)}
        </FormItem>
        <FormItem label={
          '结束日期'
        }>
          {getFieldDecorator('ended_at', {initialValue: moment(todayLastSecond())})(<DatePicker allowClear={false}
                                                                               showTime={{ format: 'HH:mm:ss' }}
                                                                               format="YYYY-MM-DD"/>)}
        </FormItem>
        <FormItem >
          <Button type="primary" icon='search' onClick={()=> {
            const {form} = this.props;
            form.validateFields((err, fieldsValue) => {
              if (err) return;

              const values = {
                ...fieldsValue,
              };
              this.setState({
                started_at: fieldsValue.started_at.format('YYYY-MM-DD HH:mm:ss'),
                ended_at: fieldsValue.ended_at.format('YYYY-MM-DD HH:mm:ss'),
              },function () {
                this.fetch({
                  type:'device',
                  channel:0,
                  page:1,
                  per_page:30,

                })
                for(let i=0;i<1;i++){

                  this.fetch({
                    type:'ball_valve',
                    channel:i,
                    page:1,
                    per_page:30,

                  })
                }
              })


            });
          }}>
            查询
          </Button>
          <Button style={{marginLeft: 8}} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>

        </FormItem>

      </Form>
    );
  }

  handleFormReset = () => {
    const {form} = this.props;
    form.resetFields();
    this.setState({
      started_at: moment().format('YYYY-MM-DD 00:00:00'),
      ended_at: todayLastSecond(),
    },function () {
      this.fetch({
        type:'device',
        channel:0,
        page:1,
        per_page:30,
      })
      for(let i=0;i<1;i++){
        this.fetch({
          type:'ball_valve',
          channel:i,
          page:1,
          per_page:30,
        })
      }
    })

  }

  render() {
    const that=this
    return <div>
      <div className="table-page history-page" style={{height:'600px'}}>
        <div >
          <div >{this.renderSimpleForm()}</div>
          <Tabs className={'left-tab'} defaultActiveKey="devices_history" tabPosition={'left'} style={{height:this.state.tableY+120+'px'}}>
            {[{name:'设备日志',key:'devices_history'},{name:'采集日志',key:'get_history'}].map((mainitem,index) => {
              return  <TabPane tab={mainitem.name} key={index}>
                <Tabs defaultActiveKey={'online_logs'} size={"small"} style={{paddingLeft:'10px'}}>

                  {
                    this.state.tabPanes.map((item,index)=>{
                      let renderTab=''
                      if(item.key==='online_logs'&&mainitem.key==='devices_history'){
                        renderTab=  <TabPane tab={item.name} key={item.key}>
                          <div>
                            <Table
                              style={{color: '#fff'}}
                              className={`custom-small-table ${this.state[`online_logs`].data.length===0&&'custom-small-table2'}`}
                              loading={this.state[`online_logs`].loading}
                              rowKey={'id'}
                              dataSource={this.state.online_logs.data}
                              columns={[
                                {
                                  title: '采集时间',
                                  dataIndex: 'created_at',
                                  width: '50%',
                                  render: (text, record) => (
                                    ellipsis2(text.slice(5),160)
                                  )
                                },
                                {
                                  title: '状态',
                                  dataIndex: 'status',
                                  render: (text, record) => {
                                    let color='',value='';
                                    switch (Number(record.status)) {
                                      case 1:
                                        color='green';
                                        value='上线';
                                        break;
                                      case -1:
                                        color='red';
                                        value='下线';
                                        break;

                                    }
                                    return <Badge color={color} text={value} />
                                  }

                                },
                              ]}
                              pagination={false}
                              size="small"
                              scroll={{x: true, y: this.state.tableY}}
                            />
                            <MyPagination className="history-pagination" searchCondition={{
                            }} meta={this.state[`online_logs`].meta} handleSearch={this.fetchLog}/>
                          </div>

                        </TabPane>
                      }
                      if(item.key==='device'&&mainitem.key==='devices_history'){
                        renderTab=<TabPane tab={item.name} key={item.key}>
                          <div >
                            <Table
                              style={{color: '#fff'}}
                              className={`custom-small-table ${this.state[`device_0`].data.length===0&&'custom-small-table2'}`}
                              loading={this.state[`device_0`].loading}
                              rowKey={'id'}
                              dataSource={this.state.device_0.data}
                              columns={[
                                {
                                  title: '采集时间',
                                  dataIndex: 'collected_at',
                                  width: 160,
                                  render: (text, record) => (
                                    ellipsis2(text.slice(5),160)
                                  )
                                },
                                {
                                  title: '运行时间(秒)',
                                  dataIndex: 'uptime',
                                  width: 150,
                                  render: (text, record) => (
                                    ellipsis2(timeStamp(record.data.uptime),130)
                                  )
                                },
                                {
                                  title: '重置原因',
                                  dataIndex: 'reset_reason',
                                  width: 80,
                                  render: (text, record) => (
                                    ellipsis2(record.data.reset_reason,80)
                                  )
                                },
                                {
                                  title:<span>供电电压(V)</span>,
                                  dataIndex: 'supply_voltage',
                                  width: 150,
                                  render: (text, record) => (
                                    ellipsis2((record.data.supply_voltage/1000).toFixed(3),100)
                                  )
                                },
                                {
                                  title: <span>信号质量(dbm)</span>,
                                  dataIndex: 'network_signal_quality',
                                  render: (text, record) => (
                                    ellipsis2(record.data.network_signal_quality,100)
                                  )
                                },
                              ]}
                              pagination={false}
                              size="small"
                              scroll={{x: true, y: this.state.tableY}}
                            />
                            <MyPagination className="history-pagination" searchCondition={{
                              type:item.key,
                              channel:0,
                            }} meta={this.state[`${item.key}_0`].meta} handleSearch={this.fetch}/>
                          </div>

                        </TabPane>
                      }
                      if(item.key==='ball_valve'&&mainitem.key==='get_history') {
                        renderTab = [0, 1].map((item2, index2) => {
                          return Boolean(that.props.config_data.ball_valve[index2]&&that.props.config_data.ball_valve[index2].enable) &&
                            <TabPane tab={that.props.config_data.ball_valve[index2].alias} key={item.key+index2}>
                              <div key={index2}>
                                <Table
                                  style={{ color: '#fff' }}
                                  className={`custom-small-table ${this.state[`ball_valve_${index2}`].data.length === 0 && 'custom-small-table2'}`}
                                  loading={this.state[`${item.key}_${index2}`].loading}
                                  rowKey={'id'}
                                  dataSource={this.state[`ball_valve_${index2}`].data}
                                  columns={[
                                    {
                                      title: '采集时间',
                                      dataIndex: 'collected_at',
                                      width: 150,
                                      render: (text, record) => (
                                        ellipsis2(text.slice(5), 150)
                                      )
                                    },
                                    {
                                      title: '状态',
                                      dataIndex: 'status',
                                      width: 150,
                                      render: (text, record) => (
                                        Number(record.data.status) === 0 ? <Badge color="#f50" text="关"/> :
                                          <Badge color="#87d068" text="开"/>
                                      )
                                    },
                                    {
                                      title: '位置',
                                      width: 150,
                                      dataIndex: 'position',
                                      render: (text, record) => {
                                        let color = '', value = ''
                                        switch (Number(record.data.position)) {
                                          case 0:
                                            value = '关';
                                            color = '#f50';
                                            break;
                                          case 1:
                                            value = '开';
                                            color = '#87d068';
                                            break;
                                          case 2:
                                            value = '移动中';
                                            color = '#108ee9';
                                            break;
                                          case 3:
                                            value = '故障';
                                            color = 'yellow';
                                            break;

                                        }
                                        return <Badge color={color} text={value}/>
                                      }
                                    },
                                    {
                                      title: '故障标志',
                                      dataIndex: 'fault_sign',
                                    },
                                  ]}
                                  pagination={false}
                                  size="small"
                                  scroll={{ x: true, y: this.state.tableY - 40 }}
                                />
                                <MyPagination className="history-pagination" searchCondition={{
                                  type: item.key,
                                  channel: index2,
                                }} meta={this.state[`${item.key}_${index2}`].meta} handleSearch={this.fetch}/>
                              </div>
                            </TabPane>
                        })
                      }
                      return renderTab
                    })
                  }
                </Tabs>
              </TabPane>
            })}
          </Tabs>


        </div>
      </div>
    {/*  <Modal
        title={false}
        destroyOnClose
        visible={this.state.chartModal}
        closable={false}
        footer={false}
        centered
        width={'900px'}
        onCancel={()=> {
          this.setState({chartModal: false,chartData:[],chartKey:''});
        }}
      >
        <ChartData chartData={this.state.chartData}  chartKey={this.state.chartKey} title={this.state.title}/>
      </Modal>*/}
    </div>
  }
}

export default BasicList;
